package edu.pitt.dbmi.odie.gapp.gwt.server.util.umls;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;

import com.allen_sauer.gwt.log.client.Log;

import edu.pitt.dbmi.odie.gapp.gwt.server.user.ODIE_ServerSideLoginInfo;

public class ODIE_UmlsServiceFetcher {
	
	private static final String CONST_UMLS_SERVICE = "umlsService" ;
	
	public static ODIE_UmlsService fetchOrCreateUmlsService(ServletConfig config, ODIE_ServerSideLoginInfo serverSideLoginInfo) {
		ODIE_UmlsService umlsService = fetchUmlsService(config) ;
		if (umlsService == null) {
			umlsService = new ODIE_UmlsService(serverSideLoginInfo) ;
			cacheUmlsService(config, umlsService) ;	
		}
		else {
			Log.debug("fetched existing umlsService") ;
		}
		return umlsService ;
	}
	
	public static void releaseUmlsService(ServletConfig config) {
		try {
			ServletContext context = config.getServletContext() ;
			context.removeAttribute(CONST_UMLS_SERVICE) ;
		}
		catch (NullPointerException x) {
			x.printStackTrace() ;
		}
	}
	
	public static ODIE_UmlsService fetchUmlsService(ServletConfig config) {
		ODIE_UmlsService umlsService = null ;
		try {
			ServletContext context = config.getServletContext() ;
			umlsService = (ODIE_UmlsService) context.getAttribute(CONST_UMLS_SERVICE) ;
		}
		catch (NullPointerException x) {
			x.printStackTrace();
		}
		return umlsService ;
	}
	
	private static void cacheUmlsService(ServletConfig config, ODIE_UmlsService umlsService) {
		try {
			config.getServletContext().setAttribute(CONST_UMLS_SERVICE, umlsService) ;
			Log.debug("cached new umlsService") ;
		}
		catch (NullPointerException x) {
			Log.warn("Failed with null servletContext.") ;
		}
	}
	

}
